package com.wanmait.schedule.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.github.pagehelper.PageInfo;
import com.wanmait.schedule.entity.Student;
import com.wanmait.schedule.entity.Teacher;
import com.wanmait.schedule.entity.TeacherRole;
import com.wanmait.schedule.service.TeacherRoleService;
import com.wanmait.schedule.service.TeacherService;
import com.wanmait.schedule.shiro.ShiroRealm;
import com.wanmait.schedule.util.AjaxResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 教师表 前端控制器
 * </p>
 *
 * @author wanmait
 * @since 2022-12-05
 */

@RestController
@RequestMapping("/manage/teacher")
public class TeacherController {
    @Resource
    private TeacherService teacherService;
    @Resource
    private TeacherRoleService teacherRoleService;
    //添加
    @PostMapping("save")
    public AjaxResult save(@RequestBody Teacher teacher){
        for (int i = 0; i < teacher.getRoleIds().length; i++) {
            System.out.println(teacher.getRoleIds()[i]);
        }
        String username = teacher.getPhone();
        String password = teacher.getIdentity().substring(12);
        teacher.setUsername(username);
        teacher.setPassword(password);
        teacherService.save(teacher);
        teacherRoleService.insertBatch(teacher.getId(),teacher.getRoleIds());
        return AjaxResult.success("添加成功");
    }

    //判断身份证
    @PostMapping("identityRepeat")
    public AjaxResult teacherIdentityRepeat(@RequestBody String identity){
        Boolean flag = teacherService.identityRepeat(identity);
        if(flag){
            return AjaxResult.success("空");
        }
        return AjaxResult.error(10001,"已存在");
    }

    //删除
    @GetMapping("delete")
    public AjaxResult delete(Integer id){
        teacherService.removeById(id);
        return AjaxResult.success("删除失败");
    }


    //根据id查询教师信息
    @GetMapping("findById")
    public AjaxResult findById(Integer id){
        Teacher teacher = teacherService.getById(id);
        List<TeacherRole> teacherRoleList = teacherRoleService.findRoleById(id);
        teacher.setRoleIds( teacherRoleList.stream()
                .map(role -> role.getRoleId() )
                .toArray(Integer[]::new));
        return AjaxResult.success("成功").put("teacher",teacher);
    }

    //修改
    @PostMapping("update")
    public AjaxResult update(@RequestBody Teacher teacher){
        teacherService.updateById(teacher);
        teacherRoleService.deleteById(teacher.getId());
        teacherRoleService.insertBatch(teacher.getId(),teacher.getRoleIds());
        //清楚缓存
        DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager) SecurityUtils.getSecurityManager();
        ShiroRealm shiroRealm = (ShiroRealm) securityManager.getRealms().iterator().next();
        shiroRealm.getAuthorizationCache().clear();

        return AjaxResult.success("修改成功");
    }

    //批量删除
    @PostMapping(value = "deleteBatch")
    public AjaxResult deleteBatch(@RequestBody Integer[] idList){
        teacherService.removeByIds(Arrays.asList(idList));
        return AjaxResult.success("删除成功");
    }
     @GetMapping("lists/{id}")
       public AjaxResult lists(@PathVariable("id")Integer id){
         return  AjaxResult.success("成功",teacherService.getById(id));

        }

    //列表分页，条件搜索
    @PostMapping("list")
    @RequiresPermissions("manage:teacher")
    public AjaxResult list(@RequestBody Teacher teacher, Integer pageNum){
        PageInfo<Teacher> pageInfo = teacherService.list(teacher,pageNum);
        return AjaxResult.success(pageInfo);
    }

    //教师总数
    @GetMapping("total")
    public AjaxResult total(){
        return AjaxResult.success("成功",teacherRoleService.count());
    }

    //获得全部教师
    @GetMapping("list")
    public AjaxResult list(){
        List<Teacher> teachers = teacherService.list();
        return AjaxResult.success(teachers);
    }
    //个人中心老师信息
    @PostMapping("teacherCenter/{id}")
    public AjaxResult teacherCenter(@PathVariable("id") Integer id){
        Teacher teacher=teacherService.getById(id);
        System.out.println(teacher);
        return AjaxResult.success("成功")
                .put("teacher",teacher);
    }
    //个人中心修改密码
    @PostMapping("teacherCenterUpdatePass")
    public AjaxResult studentCenterUpdatePass(@RequestBody Teacher teacher, String oldPassword){
        Teacher byId = teacherService.getById(teacher.getId());

        if (byId.getPassword().equals(oldPassword)) {
            teacherService.updateById(teacher);
            return AjaxResult.success("成功");
        }
        return AjaxResult.error(10002,"旧密码错误");
    }

    //导出所有教师
    @PostMapping("/export")
    public void export(HttpServletResponse response) throws IOException {

        List<Teacher> list = teacherService.list();
        //我们创建Hutool给我们写好的ExcelWrite
        ExcelWriter wirter = ExcelUtil.getWriter(true);

        wirter.addHeaderAlias("name","姓名");
        wirter.addHeaderAlias("sex","性别");
        wirter.addHeaderAlias("identity","身份证");
        wirter.addHeaderAlias("phone","电话");
        wirter.addHeaderAlias("email","邮箱");
        //hutool默认的，未添加alias的属性也会写出，如果想只写出加了别名的字段，可以调用此方法排除之
        wirter.setOnlyAlias(true);

        wirter.write(list,true);
        //我们将输出的excel文件写出到客户端直接下载
        //response为HttpServletResponse对象
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
//        response.setContentType("application/octet-stream;charset=UTF-8;");
        //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        //      response.setHeader("Content-Disposition","attachment;filename=test.xls");
        String fileName = URLEncoder.encode("所有的教师","UTF-8");
        response.setHeader("Content-Disposition","attachment;filename="+fileName+".xlsx");
        ServletOutputStream out=response.getOutputStream();
        wirter.flush(out,true);
        //关闭wirter，释放内存
        wirter.close();
        //关机输出servlet流
        IoUtil.close(out);
    }

    //修改头像
    @PostMapping("/updatePic")
    public AjaxResult updatePic(@RequestBody Teacher teacher){
        boolean b = teacherService.updateById(teacher);
        return b?AjaxResult.success("成功"):AjaxResult.error();
    }

    //修改信心
    @PostMapping("/updateTeacher")
    public AjaxResult updateTeacher(@RequestBody Teacher teacher,@RequestAttribute("teacher") Teacher t){
        teacher.setId(t.getId());
        boolean b = teacherService.updateById(teacher);
        return b?AjaxResult.success("成功"):AjaxResult.error("失败");
    }

}
